from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from rest_framework.response import Response

from users.utils import merge_cookie_redis_cart
from .models import OAuthQQUser
from .utils import generate_sign_openid
from . import serializers


# 返回qq登陸界面
class OAuthQQLoginView(APIView):
    def get(self,request):
        # 獲取參數
        state = request.query_params.get("state","/")

        # 創建對象
        oauth_qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,client_secret=settings.QQ_CLIENT_SECRET,redirect_uri=settings.QQ_REDIRECT_URI,state=state)

        # 返回qq登陸界面
        login_url = oauth_qq.get_qq_url()
        return Response({"auth_url":login_url})


# qq用戶登陸及及校驗是否綁定賬號
class OAuthQQUserView(GenericAPIView):
    serializer_class = serializers.OAuthQQUserSerializer

    # 非初次綁定用戶登陸及初次綁定頁面跳轉
    def get(self,request):
        # 獲取參數code,校驗
        code = request.query_params.get("code")
        if not code:
            return Response("code丟失了")

        # 根據code獲取access_token
        oauth_qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,redirect_uri=settings.QQ_REDIRECT_URI, state="/")
        access_token = oauth_qq.get_access_token(code)

        # 根據access_token獲取openid
        openid = oauth_qq.get_open_id(access_token)

        # 通過openid查詢qq對象用戶
        try:
            oauth_qq_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 初次授權
            sign_openid = generate_sign_openid(openid)
            return Response({"access_token":sign_openid})

        else:
            # 非初次授權
            user = oauth_qq_user.user

            # 設置token
            from rest_framework_jwt.settings import api_settings
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            response = Response({
                "token":token,
                "username":user.username,
                "user_id":user.id
            })
            # 合並購物車
            response = merge_cookie_redis_cart(request, user, response)

            return response

    # qq綁定美多用戶
    def post(self,request):
        # 獲取參數
        dict_data = request.data

        # 創建序列化器
        serializer = self.get_serializer(data=dict_data)

        # 校驗,入庫
        serializer.is_valid(raise_exception=True)
        user = serializer.save()

        # 設置token
        from rest_framework_jwt.settings import api_settings
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        response = Response({
            "token": token,
            "username": user.username,
            "user_id": user.id
        })
        # 合並購物車
        response = merge_cookie_redis_cart(request, user, response)

        # 返回響應
        return response